package com.jonychen.swagger2demo.common.config.extend;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Primary;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import springfox.documentation.service.Parameter;
import springfox.documentation.swagger2.mappers.ServiceModelToSwagger2MapperImpl;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:需要从@ApiModelProperty读取position，将position赋值给Parameter的order, 然后将List根据order输出
 * 主要是涉及：ExpandedParameterBuilderPlugin和ServiceModelToSwagger2Mapper的重新实现
 * 解决order失效问题，导致原因在于springfox.documentation.service.Operation发现原来parameters被按照字母进行了升序
 * @Author: kui.chen@100credit.com
 * @Date: 2019/9/8 15:54
 */
@Primary //同一个接口，可能会有几种不同的实现类，而默认只会采取其中一种的情况下
@Component("ServiceModelToSwagger2Mapper")
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CustomModelToSwaggerMapper extends ServiceModelToSwagger2MapperImpl {
    private static final Logger logger = LoggerFactory.getLogger(CustomModelToSwaggerMapper.class);

    @Override
    protected List<io.swagger.models.parameters.Parameter> parameterListToParameterList(List<Parameter> list) {
        //自定义规则，当access="hidden",不显示
        list=list.stream().filter(p->!"hidden".equals(p.getParamAccess())).collect(Collectors.toList());
        //list需要根据order|postion排序
        list = list.stream().sorted(Comparator.comparingInt(Parameter::getOrder)).collect(Collectors.toList());
        logger.debug("************************************list:{}", list.toString());
        return super.parameterListToParameterList(list);
    }
}
